package com.loan.controller;

import com.loan.dto.Result;
import com.loan.entity.Category;
import com.loan.repository.CategoryRepository;
import com.loan.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * Created by huxudong on 17/7/10.
 */
@Controller
@RequestMapping("admin/category")
public class CategoryController {

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private CategoryService categoryService;

    /**
     * 列表
     * @return
     */
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public String list(Model model) {
        List<Category> list = categoryService.findByFlag(0);
        model.addAttribute("list", list);
        return "category/list";
    }

    /**
     * 新增or编辑
     * @return
     */
    @RequestMapping(value = "add",method = RequestMethod.GET)
    public String add(Model model,Long id) {
        if(id != null){
            Category category = categoryRepository.getOne(id);
            model.addAttribute("category", category);
        }

        return "category/add";
    }

    /**
     * 保存
     * @return
     */
    @RequestMapping(value = "save",method = RequestMethod.POST)
    @ResponseBody
    public Result save(Category category) {
        Result result = new Result(200,"添加成功");
        if(category.getId() == null){
            category.setaTime(new Date());
        }else{
            category.setaTime(categoryRepository.getOne(category.getId()).getaTime());
        }
        if(!category.getLogo().startsWith("http://")){
            category.setLogo("http://123.56.70.231:9090"+category.getLogo());
        }
        category.setcTime(new Date());
        categoryRepository.save(category);
        return result;
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ResponseBody
    public Result delete(Long id) {
        Result result = new Result(200,"添加成功");
        categoryRepository.delete(id);
        return result;
    }

}
